<?php
/** [字段表数据模型]
 * @Author: 976123967@qq.com
 * @Date:   2015-01-09 16:51:52
 * @Last Modified by:   happy
 * @Last Modified time: 2015-03-14 17:14:01
 */
class FieldModel extends Model{
	// 表名称
	protected $tableName='model_field';

	private $cache;

	/**
	 * [_initialize 初始化]
	 * @return [type] [description]
	 */
	public function _initialize()
	{
		$this->cache = S('field');
	}

	/**
	 * [get_field_form 读取自定义模型表单]
	 * @param  [type] $mid   [description]
	 * @param  array  $value [description]
	 * @return [type]        [description]
	 */
	public function get_field_form($mid,$value=array())
	{
		$fieldAll 	= $this->cache;

		$field 		= $fieldAll[$mid];
		$modelAll   = D('Model','Logic')->get_all();
		$model 		= $modelAll[$mid];
		$form  		= array();

		foreach($field as $v)
		{
			if($v['fname']=='article_aid')
				continue;
			if($v['is_disabled'])
				continue;
			$temp = isset($value[$v['fname']])?$value[$v['fname']]:'';
			switch ($v['show_type']) {
				case 1: //文本框
					
					$result = "<input name = '{$v['fname']}' type='text' value='{$temp}' class='hd-w200' />";
					break;
				case 2: //多行文本框
					
					$result = "<textarea name = '{$v['fname']}' class='hd-w500 hd-h100'>{$temp}</textarea>";
					break;
				case 3: //完整编辑器
					
					$result =  keditor(array('name'=>$v['fname'],'content'=>$temp));
					break;
				case 4: //简单编辑器
					
					$result =  keditor(array('name'=>$v['fname'],'content'=>$temp,'style'=>2));
					break;
				case 5: //单选框
					$result ='';
					
					foreach($v['field_value'] as $f)
					{	
						$checked = $temp == $f['field_value']?"checked='checked'":"";
						$result .= "<label ><input {$checked} type='radio'  name='{$v[fname]}' value='{$f[field_value]}' /> {$f[field_value]}</label>";
					}
				
					break;
				case 6: //下拉框
					$result = "<select name='{$v["fname"]}'>";
					
					foreach($v['field_value'] as $f)
					{	
						$selected = $temp == $f['field_value']?"selected='selected'":"";
						$result .= "<option {$selected} value='{$f[field_value]}'>{$f[field_value]}</option>";
					}
					$result .= "</select>";
					break;
				case 7: //多选框
					$result ='';
					
					foreach($v['field_value'] as $f)
					{	
						$checked = strchr($temp,$f['field_value'])?"checked='checked'":"";
						$result .= "<label ><input {$checked} type='checkbox'  name='{$v[fname]}[]' value='{$f[field_value]}' /> {$f[field_value]}</label>";
					}
				
					break;
				case 8: //文件上传
					
					$result = "<input name='{$v["fname"]}' type='file'  />";
					if($temp)
					{
						$result .= "<br/> <a href='".U('down',array('aid'=>$value['aid'],'field'=>$v["fname"]))."'>下载</a>";
						$result .= "&nbsp;<a href='javascript:;' onclick='ajax_del_attachment(this,{$value[aid]},\"$v[fname]\")'>删除</a>";
						$result .= "<input type='hidden' name='table' value='article_{$model[name]}' />";
					}
					break;
				case 9: //图片上传
					
					$result = "<input name='{$v["fname"]}' type='file'  />";
					if($temp)
					{
						$result .= "<br/><img src='".__ROOT__."/".$temp."' width='100' />";
						$result .= "&nbsp;<a href='javascript:;' onclick='ajax_del_attachment(this,{$value[aid]},\"$v[fname]\")'>删除</a>";
						$result .= "<input type='hidden' name='table' value='article_{$model[name]}' />";
					}
					break;
				case 10:
					$result = '地区联动';
					break;
			}
			$form[] = array('html'=>$result,'title'=>$v['title']);
			
		}

		
		return $form;
	}


	/**
	 * [get_validate 获取js验证]
	 * @return [type]      [description]
	 */
	public function get_validate()
	{
		$cid      = I('get.cid');
		$category = S('category');
		$mid      = $category[$cid]['model_mid'];
		$field    = $this->cache[$mid];

		$valiate  = "article_title:{rule:{required:true},error:{required:'请输入文档标题'},message:'请输入文档标题'},sort:{rule:{required:true,regexp:/^\d+$/},error:{required:'请输入排序值',regexp:'排序值只能是数字'},message:'请输入排序值'},click:{rule:{required:true,regexp:/^\d+$/},error:{required:'请输入点击次数',regexp:'点击次数只能是数字'},message:'请输入点击次数'},";
		foreach($field as $v)
		{
			if($v['fname']=='article_aid' || $v['fname']=='body') continue;
			$valiate .= $v['fname'].":{ rule:{";
		
			// 验证必填
			// 规则
			if($v['require'])
			{
				$valiate .=" required:true,";
			}
			if($v['validate'])
			{
				$valiate .= "regexp:".$v['validate'].",";
			}
			$valiate = rtrim($valiate,',');


			$valiate .="},error:{";

			// 错误提示
			if($v['require'])
			{
				$valiate .= " required:'请输入".$v['title']."',";
			}
			if($v['validate'])
			{
				$valiate .= "regexp:'".$v['error']."',";
			}
			$valiate = rtrim($valiate,',')."}";
		
			if($v['require']&& ($v['show_type'] == '1'|| $v['show_type'] == '2'))
				$valiate .=",message:'请输入".$v['title']."',";
			$valiate .= "},";
		
		}
		$valiate = rtrim($valiate,',');
		return $valiate;
	}


	/**
	 * [get_lists_field 获取列表页显示的字段]
	 * @param  [type] $mid [description]
	 * @return [type]      [description]
	 */
	public function get_lists_field($mid)
	{
		$field  = $this->cache[$mid];
		$result = array();
		foreach($field as $k=>$v)
		{
			if($v['show_lists']==1)
			{
				$result[] = $v['fname'];
			}
		}
		if(!$result) return false;
		return implode(',', $result);
	}

	/**
	 * [get_img_field 图片字段]
	 * @param  [type] $mid [description]
	 * @return [type]      [description]
	 */
	public function get_img_field($mid)
	{

		$field  = $this->cache[$mid];
		$result = array();
		foreach($field as $k=>$v)
		{
			if($v['show_type']==9)
			{
				$result[] = $v['fname'];
			}
		}
		if(!$result) return false;
		return implode(',', $result);
	}
	


// -----------




	/**
	 * [alter_add_field 表中添加字段]
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	public function alter_add_field($data)
	{
		
		if($data['type']!='text')
		{
			$type = ' VARCHAR(255) NOT NULL DEFAULT "" ';
			$sql='ALTER TABLE `' . $data['table'] . '` ADD  `' . $data['fname'] . '` ' . $type;
		}
		else
		{
			$type = ' text NOT NULL ';
			$sql='ALTER TABLE `' . $data['table'] . '` ADD  `'. $data['fname'] . '` '. $type;
		}
		$sql .= " COMMENT '{$data[title]}'";

		$this->query($sql);
	}

	/**
	 * [alter_edit_field 表中修改字段]
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	public function alter_edit_field($data)
	{

		if($data['type']!='text')
		{
			$type = ' VARCHAR(255) NOT NULL DEFAULT "" ';
			$sql='ALTER TABLE `'.$data['table'].'` CHANGE  `'.$data['oldfname'].'` '. $data['fname'] . $type;
		}
		else
		{
			$type = ' text  ';
			$sql='ALTER TABLE `'.$data['table'].'` CHANGE  `'.$data['oldfname'].'` '. $data['fname'] . $type;
		}
		$sql .= "COMMENT '{$data[title]}'";

		$this->query($sql);

		//echo $sql;die;
	}

	/**
	 * [get_field_by_fid 查找单条记录中一个字段的数据，通过主键]
	 * @param  [type] $fid 	 [description]
	 * @param  [type] $field [description]
	 * @return [type]        [description]
	 */
	public function get_field_by_fid($fid,$field)
	{
		return $this->where(array('fid'=>$fid))->getField($field);
	}

	/**
	 * [drop_field 表中删除字段]
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	public function drop_field($data)
	{
		$sql = "ALTER TABLE  `" . $data['table'] ."`  DROP  ". $data['fname'];
		//echo $sql;die;
		$this->query($sql);
	}

}